package cn.tansanqinger.controller.updata;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.tansanqinger.pojo.Filemessage;
import cn.tansanqinger.pojo.User;
import cn.tansanqinger.service.root.IAdminService;
import cn.tansanqinger.util.DateUtil;
import cn.tansanqinger.util.PageData;
import cn.tansanqinger.util.Tools;

/**
 * 用于后台上传文件
 * @author C3H2
 * @time 2021.01
 */
@Controller
@RequestMapping("/upfile")
public class UpFileBackgroundController {
	
	@Autowired
	private IAdminService service;
	
	/**
	 * 用于接收相关的文件
	 * @rid 由三部分组成  xxx.xxx.xxx   任意字符.root的id.root对应的around
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/main/root/background/{rid}")
	public @ResponseBody Map<String, Object> upfileBackground(@RequestParam("file") MultipartFile file, 
			@PathVariable String rid, HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (file.isEmpty()) {
			resultMap.put("count", "-1");
			resultMap.put("data", "服务器异常");
			return resultMap;
		}
		String rootMessage[] = rid.split("\\.");
		if(rid.length()!=3) {
			//验证失败
			resultMap.put("count", "-1");
			resultMap.put("data", "服务器异常");
			return resultMap;
		}
		if(service.adminAuthentication(rootMessage[1], rootMessage[2])) {
			try {
		        String fileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
		        File upload = new File(System.getProperty("user.dir"),"/src/main/resources/resources/knowledge/html/"+fileName);
		        if(!upload.exists()) upload.mkdirs();
		        file.transferTo(upload);
				resultMap.put("count", "0");
				resultMap.put("data", "文件上传成功");
				return resultMap;
			} catch (Exception e) {}
				resultMap.put("count", "-1");
				resultMap.put("data", "服务器异常");
				return resultMap;
		}
		return resultMap;
	}
	
	/**
	 * 如果相关的信息验证失败，便显示该页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/error")
	public String error() throws Exception {
		return "error";
	}
}
